//
//  QDVersionView.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/4/5.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit

/// 文字描述的cell
private final class QDVersionTitleCell : NWTableViewCell {
    
    /// 圆形
    private let circleView = UIView()
    /// 文本描述
    let titleLabel = UILabel()
    
    /// 计算高度
    class func cellHeight(title: String) -> CGFloat {
        
        if title.isEmpty { return .leastNormalMagnitude }
        
        //获得高度
        let label = QDVersionTitleCell().titleLabel
        label.text = title
        
        return label.textRect(forBounds: CGRect(origin: .zero, size: CGSize(width: 208, height: 1000)), limitedToNumberOfLines: 0).size.height + 12//底边距
    }
    
    override func buildView() {
        super.buildView()
        
        circleView.backgroundColor = #colorLiteral(red: 0.7921568627, green: 0.8, blue: 0.7921568627, alpha: 1)
        circleView.layer.cornerRadius = 3.5
        
        titleLabel.font = Font.regular.font(size: 16)
        titleLabel.textColor = #colorLiteral(red: 0.4941176471, green: 0.5019607843, blue: 0.4941176471, alpha: 1)
        titleLabel.numberOfLines = 0
        titleLabel.lineBreakMode = .byCharWrapping
        titleLabel.text = "新版本你的还会覅是的驾驶机电脑就看看倒计时拿快递那！"
        
        contentView.addSubview(circleView)
        contentView.addSubview(titleLabel)
        
        circleView.snp.makeConstraints { (make) in
            make.width.height.equalTo(7)
            make.left.equalToSuperview().offset(34)
            make.top.equalToSuperview().offset(9)
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(0)
            make.left.equalToSuperview().offset(47)
            make.right.equalToSuperview().inset(45)
            make.bottom.equalToSuperview().inset(12)
        }
    }
}
    
    

/// 版本控制的提示视图
final class QDVersionView: NWPopWindow,UITableViewDataSource,UITableViewDelegate {

    /// 顶部的图片固定高度
    private let topImageViewHeight = CGFloat(185)
    /// 底部的按钮区域固定的高度
    private let bottomButtonViewHeight = CGFloat(76)
    
    /// 容器视图
    private let containerView = UIView()
    /// 底部白色的容器视图
    private let containerBottomView = UIView()
    /// 顶部的更新视图
    private let headerImageView = UIImageView()
    /// 发现新版本的标签
    private let titleLabel = UILabel()
    /// 展示更新内容的列表
    private let tableView = UITableView()
    /// 稍后再说的按钮
    private let closeButton = UIButton()
    /// 立即更新的按钮
    private let updateButton = UIButton()
    /// 更新的描述
    var titles = [String](){
        didSet {
            heights.removeAll()
            heights = titles.map { QDVersionTitleCell.cellHeight(title: $0) }
            //修改高度
            containerView.ritl_height = topImageViewHeight + bottomButtonViewHeight + heights.reduce(CGFloat(0)) { return $0 + $1 }
            // 修改中心点
            containerView.center = CGPoint(x: ritl_width / 2.0, y: ritl_height / 2.0 - 26)
            //修改数据
            tableView.reloadData()
        }
    }
    /// 存储所有的高度
    private var heights = [CGFloat]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //移除背景
        if let backgroundControl = backgroundView.subviews.filter({ $0 is UIControl }).first {
           backgroundControl.removeFromSuperview()
        }
        
        containerView.layer.cornerRadius = 8
        containerView.clipsToBounds = true
        containerBottomView.backgroundColor = .white
        
        headerImageView.image = "updater_top".namedImage
        
        titleLabel.text = "发现新版本!"
        titleLabel.font = Font.semibold.font(size: 20)
        titleLabel.textColor = QDColors.black
        
        tableView.backgroundColor = .white
        tableView.separatorStyle = .none
        tableView.dataSource = self
        tableView.delegate = self
        tableView.isScrollEnabled = false
        tableView.register(QDVersionTitleCell.self, forCellReuseIdentifier: "cell")
        
        closeButton.setTitle("稍后再说", for: .normal)
        closeButton.titleLabel?.font = Font.regular.font(size: 16)
        closeButton.setTitleColor(QDColors.theme, for: .normal)
        closeButton.layer.cornerRadius = 24
        closeButton.clipsToBounds = true
        closeButton.layer.borderColor = QDColors.theme.cgColor
        closeButton.layer.borderWidth = 0.5
        closeButton.controlEvents(.touchUpInside) { [unowned self](_) in
            self.dismissAnimated()
        }
        
        updateButton.titleLabel?.font = Font.semibold.font(size: 16)
        updateButton.setTitleColor(.white, for: .normal)
        updateButton.layer.cornerRadius = 24
        updateButton.clipsToBounds = true
        updateButton.setTitle("立即升级", for: .normal)
        let layer = CAGradientLayer()
        layer.position = .zero
        layer.anchorPoint = .zero
        layer.startPoint = CGPoint(x: 1, y: 0.5)
        layer.endPoint = CGPoint(x: 0, y: 0.5)
        layer.colors = [QDColors.theme.cgColor,#colorLiteral(red: 0.4509803922, green: 0.8705882353, blue: 0.5215686275, alpha: 1).cgColor]
        layer.bounds = CGRect(origin: .zero, size: CGSize(width: 121, height: 48))
        updateButton.layer.insertSublayer(layer, at: 0)
        updateButton.addTarget(self, action: #selector(updateButtonDidTap), for: .touchUpInside)
        
        contentView.addSubview(containerView)
        containerView.addSubview(containerBottomView)
        containerView.addSubview(headerImageView)
        containerView.addSubview(titleLabel)
        containerView.addSubview(tableView)
        containerView.addSubview(closeButton)
        containerView.addSubview(updateButton)
        
        containerView.frame = CGRect(origin: .zero, size: CGSize(width: 300, height: 600))//高度可变
        containerView.center = CGPoint(x: ritl_width / 2.0, y: ritl_height / 2.0)
        
        headerImageView.snp.makeConstraints { (make) in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(topImageViewHeight)
        }
        
        containerBottomView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(headerImageView.snp.bottom)//躲避阴影
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.height.equalTo(28)
            make.top.equalToSuperview().offset(141)
        }
        
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(184)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().inset(76)
        }
        
        closeButton.snp.makeConstraints { (make) in
            make.width.equalTo(121)
            make.height.equalTo(48)
            make.left.equalToSuperview().offset(20)
            make.bottom.equalToSuperview().inset(24)
        }
        
        updateButton.snp.makeConstraints { (make) in
            make.size.bottom.equalTo(closeButton)
            make.right.equalToSuperview().inset(20)
        }
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    /// 展示更新信息
    static func show(titles: [String]){
        sharedInstance().titles = titles
        super.show()
    }
    
    
    /// 更新按钮点击
    @objc func updateButtonDidTap(){
        
        let url = "https://itunes.apple.com/cn/app/id1373547573?l=zh&ls=1&mt=8"
        
        guard let openUrl = URL(string: url) else { return }
        
        if UIApplication.shared.canOpenURL(openUrl) {
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(openUrl, options: [:]) { [unowned self](_) in
                    self.dismissAnimated()
                }
            } else {
                // Fallback on earlier versions
                UIApplication.shared.openURL(openUrl)
                dismissAnimated()
            }
        }
    }
    
    
    
    override func dismissAnimated() {
        removeFromSuperview()
    }
    
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titles.count
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        
        if let updateCell = cell as? QDVersionTitleCell {
            updateCell.titleLabel.text = titles[indexPath.row]
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return heights[indexPath.row]
    }
}
